//
//  MNDReturnListViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/16.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDReturnListViewController.h"
#import "MNDReturnListCell.h"
#import "MNDReturnListHeaderView.h"
#import "ActionSheetPicker.h"
#import "HooDatePicker.h"
#import "MNDAdvancedReturnListCell.h"
#import "NSDate+JKExtension.h"
#import "NSDate+JKUtilities.h"
#import "MNDLoginUserModel.h"
#import "MNDInvestmentDetailViewController.h"

@interface MNDReturnListViewController () <UITableViewDataSource, UITableViewDelegate, HooDatePickerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *returnTotalMoneyTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *returnTotalMoneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *pricipalTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *pricipalLabel;
@property (weak, nonatomic) IBOutlet UILabel *profitTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *profitLabel;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (strong, nonatomic) MNDReturnListModel *listModel;
@property (strong, nonatomic) NSMutableArray *returnArray;

@property (strong, nonatomic) NSDate *selectedDate;
@property (weak, nonatomic) IBOutlet UIView *blankFooterView;

@property (weak, nonatomic) UIView *blankView;

@end

@implementation MNDReturnListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 200.0;
    
    self.returnArray = [NSMutableArray array];
    
    self.selectedDate = [NSDate date]; //默认本月的数据
    [self loadReturnList:_selectedDate.jk_year withMonth:_selectedDate.jk_month];
    
    self.dateLabel.text = [NSString stringWithFormat:@"%zd年%02zd月", self.selectedDate.jk_year, self.selectedDate.jk_month];
    [self.blankFooterView setHidden:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

#pragma mark - Network

- (void)loadReturnList:(NSInteger )year withMonth:(NSInteger)month {
    
    NSDictionary *params = [MNDSign signedParamWithDict: @{@"status": @(self.returnType),
                                                   @"y": @(year),
                                                   @"m": @(month)}];
    
    [self.view beginLoading];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_USER_RETURN_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [weakself.view endLoading];
            weakself.listModel = [MNDReturnListModel mj_objectWithKeyValues:responseModel.data];
            [weakself configReturnList];
        } else {
            [weakself.view endLoading];
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
        [weakself.view endLoading];
    }];
}

- (void)configReturnList {
    
    self.dateLabel.text = [NSString stringWithFormat:@"%zd年%02zd月", self.selectedDate.jk_year, self.selectedDate.jk_month];
    
    if (self.returnType == ReturnListType_unReturn) {
        self.returnTotalMoneyTitleLabel.text = [NSString stringWithFormat:@"%zd月待回款总额(元)", self.selectedDate.jk_month];
        self.pricipalTitleLabel.text = @"待收本金(元)";
        self.profitTitleLabel.text = @"待收收益(元)";
    } else {
        self.returnTotalMoneyTitleLabel.text = [NSString stringWithFormat:@"%zd月已回款总额(元)", self.selectedDate.jk_month];
        self.pricipalTitleLabel.text = @"实收本金(元)";
        self.profitTitleLabel.text = @"实收收益(元)";
    }
    self.returnTotalMoneyLabel.text = self.listModel.month_return_total;
    self.pricipalLabel.text = self.listModel.month_return_principal;
    self.profitLabel.text = self.listModel.month_return_income;
    
    NSDictionary *returnLists = self.listModel.user_return_list;
    
    [self.blankFooterView setHidden: returnLists.count];
    [self creatMaskView:!returnLists.count];
    
    [self.returnArray removeAllObjects];
    
    NSArray *dates = [returnLists.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
        
    }];
    
    NSMutableArray *reverArr = [NSMutableArray array];
    //按日期排序
    for (NSInteger i = 0; i < dates.count; i ++) {
        
        NSString *date = dates[i];
        NSArray *detailList = [MNDReturnDayDetailModel mj_objectArrayWithKeyValuesArray:returnLists[date][@"list"]];
        
        MNDReturnListSectionModel *sectionModel = [MNDReturnListSectionModel new];
        sectionModel.dayString = date;
        sectionModel.returnMoney = returnLists[date][@"days_rerurn_sum"];
        sectionModel.dayList = detailList;
        sectionModel.isExpand = NO;
        
        [reverArr addObject:sectionModel];
    }
    if (self.returnType == ReturnListType_return) {
        //倒叙排列
        [self.returnArray addObjectsFromArray:[[reverArr reverseObjectEnumerator] allObjects]];
    } else {
        [self.returnArray addObjectsFromArray: reverArr];
    }
    
    [self.tableView reloadData];
}

- (void)creatMaskView:(BOOL)isEmpty {
    if (!isEmpty) {
        if (self.blankView) {
            [self.blankView removeFromSuperview];
        }
        return;
    }
    if (self.blankView) {
        return;
    }
    UIView *maskView = [[UIView alloc]initWithFrame:CGRectMake(0, 122, kScreenWidth, kScreenHeight - 122)];
    maskView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    //    [self.view insertSubview:maskView aboveSubview:self.tableView];
    [self.tableView addSubview:maskView];
    UIImageView *imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"blankpage_emptydata"]];
    [maskView addSubview:imgV];

    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(maskView);
        make.centerY.equalTo(maskView).mas_offset(-120);
    }];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"哎呀~这里空空如也~";
    label.font = [UIFont systemFontOfSize:14.0];
    label.textColor = kColorGray;
    [maskView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imgV);
        make.top.equalTo(imgV.mas_bottom).offset(20);
    }];
    
    self.blankView = maskView;
}

- (IBAction)filterMonthAction:(id)sender {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *maxDate = [formatter dateFromString:@"2050-01-01"];
    NSDate *minDate = [formatter dateFromString:@"2013-02-01"];
    
    HooDatePicker *picker = [[HooDatePicker alloc] initDatePickerMode:HooDatePickerModeYearAndMonth
                                                              minDate:minDate
                                                           maxMamDate:maxDate
                                                    andAddToSuperView:KeyWindow];
    picker.hideSelectedLine = YES;
    picker.delegate = self;
    
    [picker show];
}

- (void)datePicker:(HooDatePicker *)datePicker dateDidChange:(NSDate *)date {
    NSLog(@"date: %@", date);
}

- (void)datePicker:(HooDatePicker *)dataPicker didSelectedDate:(NSDate *)date {
    [dataPicker removeFromSuperview];
    //所选日期与当前显示日期相同，不做请求处理
    if ([self.selectedDate jk_isSameYearAsDate:date] && [self.selectedDate jk_isSameMonthAsDate:date]) {
        return;
    }
    self.selectedDate = date;
    [self loadReturnList:self.selectedDate.jk_year withMonth:self.selectedDate.jk_month];
}

- (void)datePicker:(HooDatePicker *)datePicker didCancel:(UIButton *)sender {
    [datePicker removeFromSuperview];
}

#pragma mark - UITableView Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.returnArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    MNDReturnListSectionModel *model = self.returnArray[section];
    
    return model.isExpand? model.dayList.count : 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    static NSString *const identifier = @"header";
    MNDReturnListHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    if (!headerView) {
        headerView = [[MNDReturnListHeaderView alloc] initWithReuseIdentifier:identifier];
    }
    
    WeakSelf(self);
    
    MNDReturnListSectionModel *model = self.returnArray[section];
    headerView.model = model;
    headerView.headerClickedBlock = ^(BOOL expand) {
        [weakself updateTableViewSection:section];
    };
    
    return headerView;
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
    view.tintColor = tableView.backgroundColor;
}

- (void)updateTableViewSection:(NSInteger)section {
    //    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    //    [self.tableView endUpdates];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MNDReturnListSectionModel *sectionModel = self.returnArray[indexPath.section];
    NSArray *array = sectionModel.dayList;
    MNDReturnDayDetailModel *dayModel = array[indexPath.row];
    
    if (dayModel.is_advance_return.integerValue == 1) {
        static NSString *const cellidentifier = @"advanceCell";
        MNDAdvancedReturnListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier forIndexPath:indexPath];
        
        [cell configCellWithModel: dayModel];
        return cell;
    } else {
        static NSString *const cellIdentifier = @"cell";
        
        MNDReturnListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
        
        [cell configCellWithModel:dayModel];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MNDReturnListSectionModel *sectionModel = self.returnArray[indexPath.section];
    NSArray *array = sectionModel.dayList;
    MNDReturnDayDetailModel *dayModel = array[indexPath.row];
    
    NSLog(@"tenderid: %@", dayModel.tender_id);
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"InvestmentRecord" bundle:nil];
    MNDInvestmentDetailViewController *recordVC = [storyboard instantiateViewControllerWithIdentifier:[MNDInvestmentDetailViewController description]];
    recordVC.tenderId = [NSString stringWithFormat:@"%@", dayModel.tender_id];
    [self.navigationController pushViewController:recordVC animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
